package com.exampl.filter;

import com.alibaba.fastjson.JSON;
import com.exampl.common.BaseContext;
import com.exampl.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 过滤器
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    // 路径匹配
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        // 无需过滤的页面：静态资源与登录的动态资源
        String [] urls = new String[]{
            "/employee/login",
            "/employee/logout",
            "/backend/**",
            "/front/**",
            "/common/**",
            "/user/sendMsg",
            "/user/login"
        };
        // 无需过滤的页面，直接放行
        for(String url:urls){
            // 注意参数顺序，先填写无需过滤的页面，后填写访问的路径
            boolean b = PATH_MATCHER.match(url, uri);
            // 匹配之后直接放行
            if(b){
                filterChain.doFilter(request, response);
                return;
            }
        }
        // 已登录，直接放行
        if(request.getSession().getAttribute("employee") != null){
            // 设置ThreadLocal的值
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("employee"));
            filterChain.doFilter(request, response);
            return;
        }
        // 移动端已登录，直接放行
        if(request.getSession().getAttribute("user") != null){
            // 设置ThreadLocal的值
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("user"));
            filterChain.doFilter(request, response);
            return;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }
}
